<!--   [PAGE]] : 个人项目模板
       @Author  : ljq
       @Created : 2025/10/8
 -->
<template>
  <div class="app-container">
    <!-- ------------------------ START: 查询框 -------------------------->
    <el-form class='query' :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">

      <!--      <el-form-item>-->
      <!--        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>-->
      <!--        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
      <!--      </el-form-item>-->
      <!--    -->
    </el-form>
    <!-- ------------------------- END: 查询框 --------------------------->

    <!-- ---------------------- START: 主数据区域------------------------->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-back" size="mini" @click="toBack">返回</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddOver" v-hasPermi="[`${permi}:add`]">批量新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="[`${permi}:remove`]">批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleOrder" v-hasPermi="[`${permi}:order`]">手动下发工单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-date-picker
          v-model="orderObj.date"
          align="right"
          type="date"
          placeholder="选择日期"
          style="width: 9rem;"
          :picker-options="orderObj.pickerOptions">
        </el-date-picker>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"/>
    </el-row>


    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column label="编号" align="center" prop="id" v-if="columns[0].visible"/>
      <el-table-column label="上班时间" align="center" prop="planWorkTimeRange" v-if="columns[1].visible"  width="240%"/>
      <el-table-column label="计划工时" align="center" prop="planHour" v-if="columns[2].visible" width="120%"/>
      <el-table-column label="工人" align="center" prop="userId" v-if="columns[3].visible" width="120%">
        <template slot-scope="scope">
          <select-user isCol :value="scope.row.userId"/>
        </template>
      </el-table-column>
      <el-table-column label="工种" align="center" prop="workType" v-if="columns[4].visible" width="120%">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.business_work_type" :value="scope.row.workType"/>
        </template>
      </el-table-column>
      <el-table-column label="审批人" align="center" prop="approvalBy" v-if="columns[6].visible">
        <template slot-scope="scope">
          <select-user isCol :value="scope.row.approvalBy"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="comment" v-if="columns[5].visible"/>
      <el-table-column prop="status" align="center" label="状态" v-if="columns[7].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[8].visible"/>
      <el-table-column label="创建者" align="center" prop="createBy" v-if="columns[9].visible"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" v-if="columns[10].visible"/>
      <el-table-column label="更新者" align="center" prop="updateBy" v-if="columns[11].visible"/>

      <!-- 操作列组件 -->
      <operation-column :permi="permi" @edit="handleUpdateOver" @delete="handleDelete"/>


    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>
    <!-- ---------------------- END: 主数据区域 ------------------------>

    <!-- ------------------------ START: 弹出框 -------------------------->
    <!--  修改弹出框  -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" v-if="dialogType=='edit'">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工人" prop="userId">
              <select-user v-model="form.userId" placeholder="请选择用户" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工种" prop="workType">
              <el-select v-model="form.workType" placeholder="工种" filterable>
                <el-option v-for="dict in dict.type.business_work_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上班时间">
              <el-time-select v-model="tempWorkTimeRange1.start" placeholder="选择时间范围"
                              :picker-options="{
                                start: '05:00',
                                step: '00:15',
                                end: '23:00'
                              }" class="time-select"
                              @change="updateWorkTimeRange"/>
              -
              <el-time-select v-model="tempWorkTimeRange1.end" placeholder="选择时间范围"
                              :picker-options="{
                                start: '05:00',
                                step: '00:15',
                                end: '23:00'
                              }" class="time-select"
                              @change="updateWorkTimeRange"/>
              <span style="margin-left: 5rem"></span>
              <el-time-select v-model="tempWorkTimeRange2.start" placeholder="选择时间范围"
                              :picker-options="{
                                start: '05:00',
                                step: '00:15',
                                end: '23:00'
                              }" class="time-select"
                              @change="updateWorkTimeRange"/>
              -
              <el-time-select v-model="tempWorkTimeRange2.end" placeholder="选择时间范围"
                              :picker-options="{
                                start: '05:00',
                                step: '00:15',
                                end: '23:00'
                              }" class="time-select"
                              @change="updateWorkTimeRange"/>
            </el-form-item>
            <el-form-item label="上班时间" prop="planWorkTimeRange" v-show="false">
              <el-input v-model="form.planWorkTimeRange" placeholder="请输入上班时间区间"/>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划工时" prop="planHour">
              <el-input v-model="form.planHour" placeholder="请输入计划工时"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="时薪" prop="hourlyWage">
              <el-input v-model="form.hourlyWage" placeholder="请输入时薪"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="审批人" prop="approvalBy">
              <select-user v-model="form.approvalBy" placeholder="请选择审批人" multiple/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="状态" filterable>
                <el-option v-for="dict in dict.type.status" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="备注" prop="comment">
              <el-input v-model="form.comment" placeholder="备注"/>
            </el-form-item>
          </el-col>


        </el-row>
      </el-form>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px" v-if="dialogType=='add'">
        <el-form-item label="选择模板">
          <el-select v-model="addUser.template.selected" placeholder="请选择模板" style="width: 90%">
            <el-option v-for="item in addUser.template.list" :key="item.id" :label="` ${item.comment}           ${item.planWorkTimeRange}`" :value="JSON.stringify(item)"/>
          </el-select>
        </el-form-item>

        <div style="text-align: center">
          <el-transfer
            style="text-align: left; display: inline-block"
            v-model="addUser.target"
            filterable
            :left-default-checked="[]"
            :right-default-checked="[]"
            :titles="['选择工人', '待添加']"
            :button-texts="['撤销', '添加']"
            :data="addUser.userList">
            <span slot-scope="{ option }">{{ option.label }}</span>
          </el-transfer>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer" v-if="dialogType=='edit'">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-if="dialogType=='add'">
        <el-button type="primary" @click="submitAddUser">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- ------------------------ END: 弹出框 -------------------------->
  </div>
</template>
<script>
import {
  listProjectDetailTemplate,
  getProjectDetailTemplate,
  addProjectDetailTemplate,
  updateProjectDetailTemplate,
  delProjectDetailTemplate,
  addProjectDetailTemplateBatch,
  getProjectDetailTemplateBatch
} from "@/api/business/projectDetailTemplate";

import {addProjectDetailBatch} from "@/api/business/projectDetail"

import {initData, baseMethods} from "@/utils/basePage";

import {listUser} from "@/api/system/user";

import  {date2Str}  from "@/utils/common"

let baseData = initData();
export default {
  name: "ProjectUserTemplate",
  dicts: ['status', 'business_work_type'],
  data() {

    return {
      ...baseData,
      permi: 'business:projectTemplate',
      // 列信息
      columns: [
        {key: 0, label: `编号`, visible: false},
        {key: 1, label: `上班时间区间`, visible: true},
        {key: 2, label: `计划工时`, visible: true},
        {key: 3, label: `工人`, visible: true},
        {key: 4, label: `工种`, visible: true},
        {key: 5, label: `备注`, visible: true},
        {key: 6, label: `审批人`, visible: true},
        {key: 7, label: `状态`, visible: true},
        {key: 8, label: `创建时间`, visible: false},
        {key: 9, label: `创建者`, visible: false},
        {key: 10, label: `更新时间`, visible: false},
        {key: 11, label: `创建者`, visible: false},
      ],
      // 表单校验
      rules: {
        planWorkTimeRange: [{required: true, message: "上班时间区间不能为空", trigger: "blur"}],
        planHour: [{required: true, message: "计划工时不能为空", trigger: "blur"}],
        userId: [{required: true, message: "工人不能为空", trigger: "blur"}],
        approvalBy: [{required: true, message: "审批人不能为空", trigger: "blur"}],
        hourlyWage: [{required: true, message: "时薪不能为空", trigger: "blur"}],
      },

      // 弹出框类型
      dialogType: "",

      /// 批量新增数据
      addUser: {
        form: {},
        checked: [],
        target: [],
        template: {
          selected: "",
          list: []

        },
        userList: [],
      },

      // 接收query参数
      routeParams: {},

      tempWorkTimeRange1: {start: '', end: ''},
      tempWorkTimeRange2: {start: '', end: ''},

      // order1: "ffffff",

      // 手动下发工单数据
      orderObj: {
        pickerOptions: {
          disabledDate(time) {
            return Math.abs(time.getTime() - Date.now()) > 3600 * 1000 * 24 * 3;
          },
          shortcuts: [
            {
              text: '昨天',
              onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24);
                picker.$emit('pick', date);
              }
            },
            {
              text: '今天',
              onClick(picker) {
                picker.$emit('pick', new Date());
              }
            }, {
              text: '明天',
              onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() + 3600 * 1000 * 24);
                picker.$emit('pick', date);
              }
            }]
        },
        date: new Date()
      }

    };
  },
  created() {
    this.routeParams = this.$route.query || {};
    this.defaultForm.projectId = this.routeParams.projectId;
    this.defaultForm.type = '0';

    this.queryParams.projectId = this.routeParams.projectId;
    this.queryParams.type = '0';

    this.getList();
    this.getUserList();
    // 模板选择下拉列表
    this.getTemplateList()

  },
  methods: {
    ...baseMethods(listProjectDetailTemplate, getProjectDetailTemplate, addProjectDetailTemplate, updateProjectDetailTemplate, delProjectDetailTemplate),

    toBack() {
      this.$router.back()
    },

    /// 用户列表数据
    getUserList() {
      this.loading = true;
      this.addUser.userList = [];
      this.addUser.target = [];
      let users = [];
      let hasUsers = [];
      let hasUserF = listProjectDetailTemplate;
      hasUserF({pageNum: 1, pageSize: 10000, type: '0', projectId: this.defaultForm.projectId}).then(response => {
        hasUsers = response.rows.map(xx => Number(xx.userId)) || [];
      }).then(() => {
          listUser({pageNum: 1, pageSize: 1000}).then(response => {
            users = response.rows;
            users.forEach(xx => {
              this.addUser.userList.push({
                key: xx.userId,
                label: `${xx.nickName} - ${xx.dept.deptName}`,
                disabled: hasUsers.includes(xx.userId),
              })
            });
          });
        }
      );

      this.loading = false;
    },

    getTemplateList() {
      listProjectDetailTemplate({pageNum: 1, pageSize: 10000, type: 1, status: 1}).then(response => {
        if (response.rows.length == 0) {
          throw "请先创建模板"
        }
        this.addUser.template.list = response.rows
        this.addUser.template.selected = JSON.stringify(this.addUser.template.list[0])
        console.log("模板选择下拉框数据", this.addUser.template.list)
      });
    }
    ,

    /// [新增]提交
    submitAddUser() {
      let ret = [];
      this.addUser.target.forEach(xx => {
        ret.push({
          ...JSON.parse(this.addUser.template.selected),
          id: null,
          userId: xx,
          type: '0',
          comment: '',
        })
      });
      addProjectDetailTemplateBatch(ret).then(response => {
        this.getList();
      });
      this.open = false;

    },

    resetAddData() {
      this.getUserList();
    },

    handleAddOver() {
      this.dialogType = 'add';
      this.resetAddData()
      this.handleAdd();
    },

    handleOrder(row) {
      const ids = row.id || this.ids;
      const workDate =  date2Str(this.orderObj.date)
      console.log("日期", workDate)
      const $modal =  this.$modal;

      // const workDate = this.order.date.format('yyyy-MM-dd');
      let list = [];
      $modal.confirm('是否确认下发编号为"' + ids + '"的工单？').then(function () {
        getProjectDetailTemplateBatch(ids).then(response => {
          console.log(">>>>>>", response)
          list = response.data.map(xx => {
            return {
              planWorkTimeRange: xx.planWorkTimeRange,
              planHour: xx.planHour,
              userId: xx.userId,
              bankCardId: xx.bankCards.length > 0 ? xx.bankCards[0].id : '',
              approvalBy: xx.approvalBy,
              hourlyWage: xx.hourlyWage,
              comment: xx.comment,
              projectId: xx.projectId,
              workDate: workDate,
              workType: xx.workType,
              status: 1,
            }
          });
          // console.log("数据", list)
        }).then(() => {
          addProjectDetailBatch(list).then(xx => {
            $modal.msgSuccess("下发成功");
          });
        })
      }).catch(() => {
      });
    },

    handleUpdateOver(row) {
      this.dialogType = 'edit';
      this.handleUpdate(row);
      let [range1, range2] = row.planWorkTimeRange.split(",");
      if (range1) {
        let temp1 = range1.split("-").map(xx => xx.trim());
        this.tempWorkTimeRange1.start = temp1[0]
        this.tempWorkTimeRange1.end = temp1[1]
      }
      if (range2) {
        let temp2 = range2.split("-").map(xx => xx.trim());
        this.tempWorkTimeRange2.start = temp2[0]
        this.tempWorkTimeRange2.end = temp2[1]
      }
    },

    updateWorkTimeRange() {
      let result = '';
      {
        const {start, end} = this.tempWorkTimeRange1;
        result += `${start} - ${end}`
      }
      {
        const {start, end} = this.tempWorkTimeRange2;
        result += ` , ${start} - ${end}`
      }
      this.form.planWorkTimeRange = result;

    },

  },


};
</script>


<style scoped>
.time-select {
  width: 7.5rem !important;
  margin: 0 5px;
  font-size: 13px
}
</style>
